package com.example.admin.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.admin.entity.SysPermission;
import com.example.admin.entity.SysRole;
import com.example.admin.entity.SysUser;
import com.example.admin.entity.SysUserVo;
import com.example.admin.service.ISysPermissionService;
import com.example.admin.service.ISysRoleService;
import com.example.admin.service.ISysUserService;
import com.example.publice.aspect.annotation.Log;
import com.example.shrio.CurrentUser;
import com.example.shrio.DataScope;
import com.example.util.APIState;
import com.example.util.AjaxResult;
import com.example.util.BusinessType;
import com.example.util.encryption.EncryptionUtil;
import com.example.util.page.Pager;
import com.example.util.page.SeachParamsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wangkai
 * @since 2019-06-04
 */
@RestController
@Api(value = "系统用户Controller", tags = {"系统用户操作接口"})
@RequestMapping("/sys/sysUser")
public class SysUserController {

    @Autowired
    private ISysUserService service;

    @Autowired
    private ISysPermissionService permissionService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private DataScope dataScope;

    @ApiOperation(value = "系统用户列表", httpMethod = "POST")
    @PostMapping(value = "/page")
    public AjaxResult page(@RequestBody Pager pager) {
        Page<SysUser> page = new Page<>();
        page.setCurrent(pager.getPageNum());
        page.setSize(pager.getPageSize());
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        SeachParamsUtil.loadSearchParam(pager, queryWrapper);
        queryWrapper.ne("account", "admin");
        dataScope.dataScope(queryWrapper);
        pager.convertPage(service.page(page, queryWrapper));
        return new AjaxResult(APIState.S00, pager);
    }

    /**
     * 保存
     *
     * @param vo
     * @return
     */
    @ApiOperation(value = "系统用户新增", httpMethod = "POST")
    @Log(title = "用戶信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult save(@RequestBody SysUserVo vo) {
        SysUser sysUser = vo;
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", sysUser.getAccount());
        SysUser old = service.getOne(queryWrapper);
        if (old != null) {
            return new AjaxResult(APIState.S01, "当前账号已注册,请重新输入！！");
        }
        sysUser.setRoleList(Arrays.asList(vo.getRoles()).stream()
                .map(info -> {
                    SysRole sysRole = new SysRole();
                    sysRole.setId(info);
                    return sysRole;
                }).collect(Collectors.toList()));

        if (sysUser != null) {
            sysUser.setCreateTime(new Date());
            sysUser.setCreateBy(String.format("%s", CurrentUser.getAdminUser().getId()));
            String salt = UUID.randomUUID().toString().replace("-", "");
            String password = EncryptionUtil.encryptionMd5(sysUser.getPassword(), salt, 2);
            sysUser.setPassword(password);
            sysUser.setSalt(salt);
            sysUser.setStart(0);
            if (service.saveSysUser(sysUser)) {
                return new AjaxResult(APIState.S00, "保存成功");
            }
        }
        return new AjaxResult(APIState.S01, "保存失败");
    }

    /**
     * 修改
     *
     * @param vo
     * @return
     */
    @ApiOperation(value = "系统用户编辑", httpMethod = "PUT")
    @Log(title = "用戶信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult update(@RequestBody SysUserVo vo) {
        SysUser sysUser = vo;
        SysUser old = service.getById(sysUser.getId());
        if (old == null) {
            return new AjaxResult(APIState.S01, "当前用户不存在");
        }
        sysUser.setRoleList(Arrays.asList(vo.getRoles()).stream()
                .map(info -> {
                    SysRole sysRole = new SysRole();
                    sysRole.setId(info);
                    return sysRole;
                }).collect(Collectors.toList()));
        if (sysUser != null) {
            sysUser.setUpdateTime(new Date());
            sysUser.setUpdateBy(String.format("%s", CurrentUser.getAdminUser().getId()));
            if (!old.getPassword().equals(sysUser.getPassword())) {
                String oldPassword = EncryptionUtil.encryptionMd5(sysUser.getPassword(), old.getSalt(), 2);
                if (!old.getPassword().equals(oldPassword)) {
                    String salt = UUID.randomUUID().toString().replace("-", "");
                    String password = EncryptionUtil.encryptionMd5(sysUser.getPassword(), salt, 2);
                    sysUser.setPassword(password);
                    sysUser.setSalt(salt);
                }
            }
            if (service.updateSysUser(sysUser)) {
                return new AjaxResult(APIState.S00, "保存成功");
            }
        }
        return new AjaxResult(APIState.S01, "保存失败");
    }

    @ApiOperation(value = "系统用户编辑", httpMethod = "PUT")
    @Log(title = "用戶信息", businessType = BusinessType.UPDATE)
    @PutMapping("updateUser")
    public AjaxResult updateUser(@RequestBody SysUser sysUser) {
        SysUser cuser = CurrentUser.getAdminUser();
        if (sysUser != null) {
            sysUser.setUpdateTime(new Date());
            sysUser.setUpdateBy(String.format("%s", CurrentUser.getAdminUser().getId()));
            if (!cuser.getPassword().equals(sysUser.getPassword())) {
                String oldPassword = EncryptionUtil.encryptionMd5(sysUser.getPassword(), cuser.getSalt(), 2);
                if (!cuser.getPassword().equals(oldPassword)) {
                    String salt = UUID.randomUUID().toString().replace("-", "");
                    String password = EncryptionUtil.encryptionMd5(sysUser.getPassword(), salt, 2);
                    sysUser.setPassword(password);
                    sysUser.setSalt(salt);
                }
            }
            if (sysUser.insertOrUpdate()) {
                return new AjaxResult(APIState.S00, "修改成功,重新登录后生效！！！");
            }
        }
        return new AjaxResult(APIState.S01, "修改失败");
    }

    /**
     * 刪除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "系统用户删除", httpMethod = "DELETE")
    @Log(title = "用戶信息", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/{ids}")
    public AjaxResult delete(@PathVariable Integer[] ids) {
        if (ids != null) {
            if (service.deleteSysUser(ids)) {
                return new AjaxResult(APIState.S00, "删除成功");
            }
        }
        return new AjaxResult(APIState.S01, "删除失败");
    }

    @ApiOperation(value = "重置密码", httpMethod = "PUT")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PutMapping("reset")
    public AjaxResult resetPass(Integer id) {
        SysUser sysUser = service.getById(id);
        if (sysUser != null) {
            String salt = UUID.randomUUID().toString().replace("_", "");
            String newPassword = EncryptionUtil.encryptionMd5("123456", salt, 2);
            sysUser.setPassword(newPassword);
            sysUser.setSalt(salt);
            if (service.updateById(sysUser)) {
                return new AjaxResult(APIState.S00, "重置成功");
            }
        }
        return new AjaxResult(APIState.S01, "重置失败");
    }

    @ApiOperation(value = "用户启用/停用", httpMethod = "PUT")
    @Log(title = "用户启用/停用", businessType = BusinessType.UPDATE)
    @PutMapping("start")
    public AjaxResult start(Integer id) {
        SysUser sysUser = service.getById(id);
        if (sysUser != null) {
            if (sysUser.getStart() == 1) {
                sysUser.setStart(0);
            } else {
                sysUser.setStart(1);
            }
            sysUser.setUpdateTime(new Date());
            sysUser.setUpdateBy(String.format("%s", CurrentUser.getAdminUser().getId()));
            if (service.updateById(sysUser)) {
                return new AjaxResult(APIState.S00, "更改成功");
            }
        }
        return new AjaxResult(APIState.S01, "更改失败");
    }


    @ApiOperation(value = "用户信息", httpMethod = "GET")
    @GetMapping("getUserInfo")
    public AjaxResult getUserInfo() {
        SysUser sysUser = CurrentUser.getAdminUser();
        List<SysPermission> list = permissionService.getUserList(sysUser);
        List<SysPermission> permissions = list.stream().filter(info -> info.getFlag().intValue() == 0).collect(Collectors.toList());
        List<SysRole> roles = roleService.getRoleList(sysUser.getId());
        Map<String, Object> result = new HashMap<>();
        result.put("userInfo", sysUser);
        result.put("roles", roles.stream().map(info -> info.getCode()).collect(Collectors.toList()));
        result.put("permission", permissions.stream().map(info -> info.getPermission()).collect(Collectors.toList()));
        return new AjaxResult(APIState.S01, result);
    }

}
